package com.orangelife.mobile.goodsOrder.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.view.ProgressWheel;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.adapter.MyImageViewGridAdapter;
import com.orangelife.mobile.common.biz.Photo;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.common.view.NewConfirmDialog;
import com.thirdsdk.qiniu.QiniuService;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsOrder.biz.OrderHttp;
import com.orangelife.mobile.photo.ImageActivity;
import com.orangelife.mobile.photo.MyGridView;
import com.orangelife.mobile.photo.PhotoActivity;
import com.orangelife.mobile.util.ToastHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 取消订单，申请退款
 * Created by YangWei
 * on 2016/1/14.
 */
public class CancelOrderActivity extends OrangeLifeBaseActivity implements View.OnClickListener {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.progress)
    ProgressWheel progress;
    @Bind(R.id.tvReasonTip)
    TextView tvReasonTip;
    @Bind(R.id.tvReason)
    TextView tvReason;
    @Bind(R.id.tvRefundMoney)
    TextView tvRefundMoney;
    @Bind(R.id.myGridview)
    MyGridView myGridView;
    @Bind(R.id.tvPhotoTip)
    TextView tvPhotoTip;
    @Bind(R.id.tvInfo1)
    TextView tvInfo1;
    @Bind(R.id.llInfo1)
    LinearLayout llInfo1;
    @Bind(R.id.llInfo2)
    LinearLayout llInfo2;
    @Bind(R.id.btnSubmit)
    Button btnSubmit;
    private MyImageViewGridAdapter gvAdapter;
    private List<String> paths;
    private List<String> reason;
    Bundle bundle;
    private int type;
    private String orderID;
    private ArrayAdapter adapter;
    private String refundMoney;
    private String applicationReasons;
    private Dialog builder = null;
    //列表
    private ListView lv = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cancel_order);
        ButterKnife.bind(this);
        OrderHttp.getCancelReason(handler);
        initView();
    }

    private Dialog dialog;

    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    private void initView() {
        progress.setVisibility(View.VISIBLE);
        bundle = getIntent().getExtras();
        type = bundle.getInt("type");//0，取消订单 1，申请退款
        orderID = bundle.getString("orderID");
        refundMoney = bundle.getString("refundMoney");
        reason = new ArrayList<>();
        if (type == 0) {
            tvTitle.setText("取消订单");
            myGridView.setVisibility(View.GONE);
            llInfo2.setVisibility(View.GONE);
            llInfo1.setVisibility(View.VISIBLE);
            tvPhotoTip.setVisibility(View.GONE);
            tvReasonTip.setText("取消订单原因：");
        } else {
            tvTitle.setText("申请退款");
            myGridView.setVisibility(View.VISIBLE);
            llInfo1.setVisibility(View.GONE);
            llInfo2.setVisibility(View.VISIBLE);
            tvReasonTip.setText("退款原因：");
            tvPhotoTip.setVisibility(View.VISIBLE);
            setGridView();
        }

        tvRefundMoney.setText(Constant.RMB_FLAG+ refundMoney);

        btnSubmit.setOnClickListener(this);
        tvReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
//        spSelectReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                applicationReasons = reason.get(position).toString();
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//            }
//        });
    }
    /** 显示对话框 **/
    public void showDialog() {
        builder = new Dialog(this,R.style.NewDialogStyle);
        builder.setTitle("请选择原因");
        builder.show();
        LayoutInflater inflater = LayoutInflater.from(this);
        View viewDialog = inflater.inflate(R.layout.dialog_select, null);
        Display display = this.getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        //设置对话框的宽高
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width * 90 / 100,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        builder.setContentView(viewDialog, layoutParams);

        lv = (ListView) viewDialog.findViewById(R.id.lv_remain_item);
        adapter = new ArrayAdapter(CancelOrderActivity.this, android.R.layout.select_dialog_item, reason);

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                applicationReasons = reason.get(position).toString();
                builder.dismiss();
                tvReason.setText(applicationReasons);
            }

        });
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.submit_success));
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
                case 2:
                    Map<String, Object> map = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    if (type == 0) {
                        reason.addAll((List<String>) map.get("canceling"));
                    } else {
                        reason.addAll((List<String>) map.get("applyRefund"));
                    }
                    progress.setVisibility(View.GONE);
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                case Constant.WHAT_ERROR_HTTP:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    };

    /**
     * 给照片gridview设置apdater和监听事件
     */
    private void setGridView() {
        /** 设置adapter */
        paths = new ArrayList<String>();
        gvAdapter = new MyImageViewGridAdapter(
                CancelOrderActivity.this, paths, 5);
        myGridView.setAdapter(gvAdapter);
        gvAdapter.notifyDataSetChanged();
        /** 监听事件 */
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                if (position == paths.size()) {
                    Intent intent = new Intent(
                            CancelOrderActivity.this,
                            PhotoActivity.class);
                    startActivityForResult(intent, 5);
                } else {

                    Intent intent = new Intent(
                            CancelOrderActivity.this,
                            ImageActivity.class);
                    intent.putExtra("position", position);
                    intent.putExtra("path", paths.get(position));
                    startActivityForResult(intent, 88);
                }
            }
        });

    }

    Photo photo = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                String photoPath = data.getStringExtra("photoPath");
                Context cxt = CancelOrderActivity.this;
                paths.add(photoPath);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            } else {
                if (photo.photoUri != null) {
                    String photoPath = photo.photoUri.getPath();
                    paths.add(photoPath);
                    gvAdapter.resetImage(paths);
                    gvAdapter.notifyDataSetChanged();
                }

            }
        } else if (requestCode == 6 && resultCode == 99) {
            if (data != null) {
                String photoPath = Photo.getPath(data);
                Context cxt = CancelOrderActivity.this;
                paths.add(photoPath);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            }

        } else if (requestCode == 88 && resultCode == 88) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                int position = bundle.getInt("position");
                paths.remove(position);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            }
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 处理后的照片地址
     */
    private String fileName = null;

    @Override
    public void onClick(View v) {
        applicationReasons=tvReason.getText().toString();
        if (StringUtil.isBlank(applicationReasons)||applicationReasons.equals("请选择")) {
            ToastHelper.getInstance().displayToastWithQuickClose("请选择原因");
            return;
        }

        final ConfirmDialog dialog=new ConfirmDialog(this,"温馨提示","您确定要取消订单吗?","取消","确定");
        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog.dismiss();
                return;
            }

            @Override
            public void doRight() {
                dialog.dismiss();
                final Map<String, Object> map = new HashMap<>();
                map.put("orderID", orderID);
                map.put("applicationReasons", applicationReasons);
                if (type == 1) {
                    if (paths.size() != 0) {
                        getDataFromServer();
                        QiniuService qiniu = new QiniuService();
                        qiniu.imgUpload(paths, new QiniuService.QiniuListener() {
                            @Override
                            public void request(String fileNames) {
                                if (fileNames.equals("500")) {
                                    ToastHelper.getInstance()._toast(
                                        getResources().getString(
                                            R.string.photo_save_faild));
                                    return;
                                }

                                if (fileNames == null) {
                                    map.put("photo", "");
                                } else {
                                    map.put("photo", fileNames);
                                } //									sendRepair(fileName);

                                OrderHttp.postCancelRequest(map, handler);
                            }
                        });
                    }else{
                        getDataFromServer();
                        OrderHttp.postCancelRequest(map, handler);
                    }
                }else{
                    getDataFromServer();
                    OrderHttp.postCancelRequest(map, handler);
                }
            }
        });

        dialog.show();

    }
}
